/**
 * Copyright (c) 2024,  科泰集团教研团队
 * 版权所有，请勿侵权
 */
package com.ktjiaoyu.controller;

import java.util.*;

import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.Supplier;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.Supplier;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.UploadService;
import com.ktjiaoyu.utils.Constants;
import com.ktjiaoyu.utils.Page;
import com.ktjiaoyu.service.SupplierService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author 科泰集团教研团队
 * @packageName com.ktjiaoyu
 * @fileName SupplierController.java
 * @createTime 2024/10/18 23:25:38
 * @lastModify 2024/10/18 23:25:38
 * @version 1.0.0
 */
@Controller
@RequestMapping("/main/supplier")
public class SupplierController extends BaseController{
    private static final Logger LOGGER =
            LoggerFactory.getLogger(SupplierController.class);

    @Autowired
    private SupplierService supplierService;
    @Autowired
    @Qualifier("toLocalUploadService")
    private UploadService uploadService;

    @RequestMapping("/page")
    public String page(Model model, Supplier condition,
                       @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){
        Page<Supplier> page = null;
        try {
            page = supplierService.findPage(condition, pageNo, pageSize);
            model.addAttribute("pageInfo", page);
            model.addAttribute("condition", condition);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "supplier/page";
    }

    /** 跳转到save.jsp页面的接口 */
    @GetMapping("/save")
    public String toSave(Model model){
        try {
            // 回显数据时需要supplier，这里给个空对象避免出错
            model.addAttribute("supplier", new Supplier());
        } catch (Exception e) {
            LOGGER.error("SupplierController中的toSave方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "supplier/save";
    }

    /** 查询供应商信息并跳转修改页（共用save.jsp) */
    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id, Model model){
        Supplier supplier = null;
        try {
            supplier = supplierService.findById(id);
            // 回显数据时需要supplier，这里给个空对象避免出错
            model.addAttribute("supplier", supplier);
        } catch (Exception e) {
            LOGGER.error("SupplierController中的toEdit方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "supplier/save";
    }

    /** 保存或修改数据接口 */
    @PostMapping("/save")
    public String doSave(Supplier supplier,
                         MultipartFile bizPic){
        // 允许的上传图片后缀
        String[] allowImageExt = {"jpg", "jpeg", "png", "gif", "bmp"};
        try {
            // 上传证件照
            if(bizPic != null){
                // 调用上传文件服务，返回上传成功后的路径，为null表示没上传
                String bizPicPath = uploadService.uploadFile(bizPic, allowImageExt);
                supplier.setBizPicPath(bizPicPath);
            }

            // 通过父类的session方法获取登录供应商，由于泛型自动转换无需强转
            SysUser loginUser = session(Constants.SESSION_USER);
            if(supplier.getId() == null){
                // 如果是添加供应商，关联创建供应商为当前登陆供应商
                supplier.setCreatedUserId(loginUser.getId());
                supplier.setCreatedTime(new Date());
            }else{
                // 如果是修改供应商，关联修改供应商为当前登陆供应商
                supplier.setUpdatedUserId(loginUser.getId());
                supplier.setUpdatedTime(new Date());
            }
            // 新增和修改公用同一个业务方法
            boolean ok = supplierService.saveOrUpdate(supplier);
            if(ok){
                // 保存成功，跳回列表页面
                return redirect("/main/supplier/page");
            }
        } catch (Exception e) {
            LOGGER.error("SupplierController中的doSave方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "supplier/save";
    }

    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") Long id,
                       Model model){
        Supplier supplier = null;
        try {
            supplier = supplierService.findById(id);
            model.addAttribute("supplier", supplier);
        } catch (Exception e) {
            LOGGER.error("SupplierController中的view方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "supplier/view";
    }

    @ResponseBody
    @GetMapping("/supCodeExist")
    public String supCodeExist(@RequestParam String supCode){
        LOGGER.debug("检查供应商编号supCodeExist={}的供应商是否存在", supCode);
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        if(StringUtils.isEmpty(supCode)){
            resultMap.put("exist", 0);
        }else{
            try {
                Supplier supplier = supplierService.findBySupCode(supCode);
                if(null != supplier) {
                    // 已经存在，设置为1
                    resultMap.put("exist", 1);
                }else {
                    resultMap.put("exist", 0);
                }
            } catch (Exception e) {
                LOGGER.error("SupplierController中的" +
                        "supCodeExists方法执行发生错误。", e);
                resultMap.put("error", "出现异常，请联系管理员处理！");
            }
        }
        return JSON.toJSONString(resultMap);
    }

    @GetMapping(value = "/{id}/view")
    @ResponseBody
    public Map ajaxView(@PathVariable("id") Long id){
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        Supplier info = null;
        try {
            info = supplierService.findById(id);
            if(info != null){
                resultMap.put("code", 200);
                resultMap.put("data", info);
            }else{
                resultMap.put("code", 500);
            }
        } catch (Exception e) {
            LOGGER.error("SupplierController中的" +
                    "ajaxView方法执行发生错误。", e);
            resultMap.put("code", 500);
        }
        return resultMap;
    }

}
